<?php

namespace app\api\service\order;

use app\common\model\dealer\OrderNew;
use app\common\model\User;
use app\common\service\order\Refund as RefundService;
use think\Hook;
use app\api\service\Basics;
use app\api\model\User as UserModel;
use app\api\model\Order as OrderModel;
//use app\api\model\WxappPrepayId as WxappPrepayIdModel;
use app\api\model\user\BalanceLog as BalanceLogModel;
use app\api\model\user\ShareLog as ShareLogModel;
use app\common\service\goods\source\Factory as StockFactory;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
/**
 * 订单支付成功服务类
 * Class PaySuccess
 * @package app\api\service\order
 */
class PaySuccess extends Basics
{
    // 订单模型
    public $model;

    // 当前用户信息
    private $user;

    /**
     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo)
    {
        // 实例化订单模型
        $this->model = OrderModel::getPayDetail($orderNo);
        if (!empty($this->model)) {
            $this->wxappId = $this->model['wxapp_id'];
        }
        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);

    }

    /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }

    /**
     * 订单支付成功业务处理
     * @param $payType
     * @param array $payData
     * @return bool
     */
    public function onPaySuccess($payType, $payData = [])
    {
        if (empty($this->model)) {
            $this->error = '未找到该订单信息';
            return false;
        }
        // 更新付款状态
        $status = $this->updatePayStatus($payType, $payData);
        // 订单支付成功行为
        if ($status == true) {
            Hook::listen('order_pay_success', $this->model, OrderTypeEnum::MASTER);
            //记录发放佣金
         //   OrderNew::Grade($this->model,1);
        }
        return $status;
    }

    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function updatePayStatus($payType, $payData = [])
    {
        // 验证余额支付时用户余额是否满足
        if ($payType == PayTypeEnum::BALANCE) {
            if ($this->user['balance'] < $this->model['pay_price']) {
                $this->error = '用户余额不足，无法使用余额支付';
                return false;
            }
        }
        // 事务处理
        $this->model->transaction(function () use ($payType, $payData) {
            // 更新订单状态
            $this->updateOrderInfo($payType, $payData);
            // 累积用户总消费金额
            $this->user->setIncPayMoney($this->model['pay_price']);
            // 记录订单支付信息
            $this->updatePayInfo($payType);
            $this->oneSwap();
            //记录发放佣金
            OrderNew::Grade($this->model,1);
            //累计消费金额 做升级准备
            $this->setIncUserExpend([$this->model]);
        });
        return true;
    }
    private function setIncUserExpend($orderList)
    {
        // 计算并累积实际消费金额(需减去售后退款的金额)
        $userData = [];
        foreach ($orderList as $order) {
            // 订单实际支付金额
            $expendMoney = $order['pay_price'];
            // 减去订单退款的金额
            foreach ($order['goods'] as $goods) {
                if (
                    !empty($goods['refund'])
                    && $goods['refund']['type']['value'] == 10      // 售后类型：退货退款
                    && $goods['refund']['is_agree']['value'] == 10  // 商家审核：已同意
                ) {
                    $expendMoney -= $goods['refund']['refund_money'];
                }
            }
            !isset($userData[$order['user_id']]) && $userData[$order['user_id']] = 0.00;
            $expendMoney > 0 && $userData[$order['user_id']] += $expendMoney;
        }
        // 累积到会员表记录
        UserModel::onBatchIncExpendMoney1($userData,$order);
       // UserModel->onBatchIncExpendMoney($userData,$order);
        return true;
    }
    /**
     * 更新订单记录
     * @param $payType
     * @param $payData
     * @return false|int
     * @throws \Exception
     */
    private function updateOrderInfo($payType, $payData)
    {
        // 更新商品库存、销量
        StockFactory::getFactory($this->model['order_source'])->updateStockSales($this->model['goods']);
        // 整理订单信息
        $order = [
            'pay_type' => $payType,
            'pay_status' => 20,
            'pay_time' => time()
        ];
        if ($payType == PayTypeEnum::WECHAT) {
            $order['transaction_id'] = $payData['transaction_id'];
        }
        // 更新订单状态
        return $this->model->save($order);
    }

    /**
     * 记录订单支付信息
     * @param $payType
     * @throws \think\Exception
     */
    private function updatePayInfo($payType)
    {
        // 余额支付
        if ($payType == PayTypeEnum::BALANCE) {
            // 更新用户余额
            $this->user->setDec('balance', $this->model['pay_price']);
            BalanceLogModel::add(SceneEnum::CONSUME, [
                'user_id' => $this->user['user_id'],
                'money' => -$this->model['pay_price'],
            ], ['order_no' => $this->model['order_no']]);
        }
        // 微信支付
        if ($payType == PayTypeEnum::WECHAT) {
            // 更新prepay_id记录
//            WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::MASTER);
        }
    }
    /**
     * 记录一元换购分享
     * @param $payData
     * @throws \think\Exception
     */
    private function oneSwap()
    {
        if($this->model['order_source'] == 40){
            $order = db('order')->where(['user_id'=>$this->model['share_uid'],'share_goods_id'=>$this->model['share_goods_id'],'return_type'=>1])->find();
           if($this->model['share_uid'] > 0){
               $values = db('sharp_setting_one')->where(['key'=>'basic'])->value('values');
               $sharp_goods_one = db('sharp_goods_one')->field('sharp_goods_id,goods_id')->where(['is_delete'=>0,'status'=>1,'goods_id'=>$this->model['share_goods_id']])->find();
               $array = json_decode($values, true);
               //属于一元换购的商品 返换金额
               if($sharp_goods_one){
                   $price = $this->model['pay_price'] - $this->model['express_price'];
                   $pay_price = bcdiv($price,$array['order']['number'],2);
                   $shengyu = $price - $order['share_price'];
                   if($pay_price >= $shengyu){
                       db('user')->where(['user_id'=>$order['user_id']])->setInc('balance',$shengyu);
                       db('order')->where(['order_id'=>$order['order_id']])->setInc('share_price',$shengyu);
                       db('order')->where(['order_id'=>$order['order_id']])->setField('return_type',2);
                       // 执行原路退款
                       (new RefundService)->execute($order, $shengyu);
                   }else{
                       db('user')->where(['user_id'=>$this->model['share_uid']])->setInc('balance',$pay_price);
                       db('order')->where(['order_id'=>$order['order_id']])->setInc('share_price',$pay_price);
                       (new RefundService)->execute($order, $pay_price);
                   }

                   ShareLogModel::add(SceneEnum::CONSUME, [
                       'user_id' => $order['user_id'],
                       'money' => $pay_price,
                   ], ['order_no' => $this->model['order_no']]);
               }

           }


            //pay_price express_price

//            if($order['share_num'] >= $array['order']['number']){
//                //执行退款操作
//
//            }else{
//                db('order')->where(['order_id'=>$order['order_id']])->setInc('share_num',1);
//                $share_num = db('order')->where(['order_id'=>$order['order_id']])->value('share_num');
//                if($share_num >= $array['order']['number']){
//                    //执行退款操作
//                    //记录退款明细
//                    ShareLogModel::add(SceneEnum::CONSUME, [
//                        'user_id' => $this->user['user_id'],
//                        'money' => -$this->model['pay_price'],
//                    ], ['order_no' => $this->model['order_no']]);
//                }
//
//            }
        }
    }
}